package com.gykfbxxh.imovie.view.filmsdetail.acitivity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.utils.util.AppTools;
import com.app.utils.util.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.base.BaseActivity;
import com.gykfbxxh.imovie.bean.comment.FilmComment;
import com.gykfbxxh.imovie.bean.film.FilmBean;
import com.gykfbxxh.imovie.bean.film.FilmDetailInfo;
import com.gykfbxxh.imovie.bean.film.FilmEntity;
import com.gykfbxxh.imovie.bean.film.FilmSourceBean;
import com.gykfbxxh.imovie.bean.film.FilmVideoLocal;
import com.gykfbxxh.imovie.bean.news.ShareBean;
import com.gykfbxxh.imovie.config.URIContant;
import com.gykfbxxh.imovie.custom.view.LoadView;
import com.gykfbxxh.imovie.listener.CommentListener;
import com.gykfbxxh.imovie.listener.HttpListener;
import com.gykfbxxh.imovie.manager.AppManager;
import com.gykfbxxh.imovie.manager.UserInforManager;
import com.gykfbxxh.imovie.utils.AnimationUtils;
import com.gykfbxxh.imovie.utils.AppShareUtils;
import com.gykfbxxh.imovie.utils.CommentUtils;
import com.gykfbxxh.imovie.utils.HttpUtils;
import com.gykfbxxh.imovie.view.filmsdetail.view.CommentListView;
import com.gykfbxxh.imovie.view.filmsdetail.view.DetailFilmView;
import com.gykfbxxh.imovie.view.filmsdetail.view.DetailScrollView;
import com.gykfbxxh.imovie.view.main.MainActivity;
import com.gykfbxxh.imovie.view.user.activity.LoginActivity;
import com.umeng.socialize.UMShareAPI;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;

import java.util.HashMap;
import java.util.List;

/**
 * 电影详情页
 */

public class FilmDetailActivity extends BaseActivity implements View.OnClickListener {

    private DetailScrollView mScrollView;//滑动布局
    private CommentListView mCommentListView;//评论载体

    private DetailFilmView detailFilmView;//内容view
    private String fObjectid;//文章id
    private LoadView lv_loadview;
    private TextView tv_comment;
    private LinearLayout ll_back_gg,ll_back_gg_black;
    private RelativeLayout rl_headview,rl_headview_while;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSlideBack = false;
        //获取传输数据
        mPageName = "FilmDetailActivity";
        isInit = false;
        getIntentData();
        super.onCreate(savedInstanceState);
        //加入到新闻详情栈中
        AppManager.getAppManager().addDetailActivity(this);

        setContentView(R.layout.activity_film_detail);
        initView();//初始化页面
        loadData();//初始化页面数据
//        querySaveNews();//查询本地收藏
    }

    private void getIntentData() {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        fObjectid = intent.getStringExtra(PARAMETER1);
        if(TextUtils.isEmpty(fObjectid)) {
            onBackPressed();
        }
    }

    private void initView() {
        rl_headview = (RelativeLayout)findViewById(R.id.rl_headview);
        rl_headview_while = (RelativeLayout)findViewById(R.id.rl_headview_while);
        rl_headview_while.setAlpha(0f);
        ll_back_gg = (LinearLayout)findViewById(R.id.ll_back_gg);
        ll_back_gg_black = (LinearLayout)findViewById(R.id.ll_back_gg_black);
        tv_comment = (TextView)findViewById(R.id.tv_comment);
        tv_comment.setOnClickListener(this);
        lv_loadview = (LoadView)findViewById(R.id.lv_loadview);
        lv_loadview.setErrorPageClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadData();
            }
        });
        mScrollView = (DetailScrollView) findViewById(R.id.psv_psrsolview);
        detailFilmView = (DetailFilmView) findViewById(R.id.dnv_newsview);
        detailFilmView.init(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            detailFilmView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    if(scrollY==0) {
                        rl_headview_while.setAlpha(0f);
                    }else if(scrollY>=800) {
                        rl_headview_while.setAlpha(1f);
                    }else {
                        rl_headview_while.setAlpha(scrollY/800f);
                    }
                }
            });
        }
        detailFilmView.httpName = mPageName;
        ll_back_gg.setOnClickListener(this);
        ll_back_gg_black.setOnClickListener(this);
        this.mCommentListView = (CommentListView) findViewById(R.id.prlv_listview);

    }

    private void loadData() {
        lv_loadview.showLoadPage("正在努力请求数据...");
        commitPlayLog();//提交播放日志
        getFilmData();//获取电影信息
        getGuessFilmListData();//猜你喜欢地址
        getFilmInfoData();//获取电影地址信息
        getFilmSourceData();//获取电影源
        mScrollView.scrollToFirstView();
    }

    @Override
    protected void onPause() {
        super.onPause();
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
//        JCVideoPlayer.releaseAllVideos();
        //检查详情有多少个
        int detailActivityCount = AppManager.getAppManager().getDetailActivityCount();
//        LogUtils.e("gzq", "maxMemory = "+maxMemory+"    freeMemory = "+freeMemory);
        if (detailActivityCount > 2) {
//            LogUtils.e("gzq", "detailActivityCount = "+detailActivityCount+"    ___"+this);
            AppManager.getAppManager().finishFirstDetailActivity();
        }
    }

    /**
     * 提交播放日志
     */
    private void commitPlayLog() {
        HashMap<String,String> parms = new HashMap<>();
        parms.put("classtype","1");
        parms.put("objectid",fObjectid);
        parms.put("apptype","4");
        parms.put("phoneSN", AppTools.getIMEI());

        HttpUtils.addPostResultRequest(URIContant.ADDPLAYLOG, mPageName, parms, null);
        mScrollView.scrollToFirstView();
    }

    /**
     * 获取电影信息
     */
    private void getFilmData() {
        HttpUtils.addGetRequest(URIContant.GETFILMINFO + fObjectid, new TypeToken<FilmDetailInfo>() {
        }.getType(), mPageName, new HttpListener<FilmDetailInfo>() {
            @Override
            public void onError(VolleyError error) {
                lv_loadview.showErrorPage();
                mScrollView.scrollToFirstView();
            }

            @Override
            public void onSuccess(FilmDetailInfo response) {
                if(response!=null) {
                    FilmDetailInfo.ResultBean result = response.getResult();
                    if(result!=null&&result.getFilm()!=null&&result.getFilminfo()!=null&&result.getVideoscore()!=null) {
                        detailFilmView.setFilmData(result,null,null,null, mScrollView);
                        lv_loadview.showSuccess();
                    }else {
                        lv_loadview.showErrorPage();
                    }
                    mScrollView.scrollToFirstView();
                }
            }
        });
    }

    /**
     * 猜你喜欢地址
     */
    private void getGuessFilmListData() {
        HttpUtils.addGetRequest(URIContant.HOTFILM , new TypeToken<FilmBean<FilmEntity>>() {
        }.getType(), mPageName, new HttpListener<FilmBean<FilmEntity>>() {
            @Override
            public void onError(VolleyError error) {
                mScrollView.scrollToFirstView();
            }

            @Override
            public void onSuccess(FilmBean<FilmEntity> response) {
                if(response!=null&&response.getResult()!=null) {
                    List<FilmEntity> guesslist = response.getResult();
                    detailFilmView.setFilmData(null,guesslist,null,null,mScrollView);
                }
                mScrollView.scrollToFirstView();
            }
        });
    }

    /**
     * 获取电影地址信息
     */
    private void getFilmInfoData() {
        HashMap<String,String> map = new HashMap<>();
        map.put("objectid",fObjectid);
        map.put("classtype","1");
        map.put("fSourcetype","0");
        HttpUtils.addPostRequest(URIContant.GETVIDEOLOCAL1_0, new TypeToken<FilmVideoLocal>() {
        }.getType(), mPageName, map, new HttpListener<FilmVideoLocal>() {
            @Override
            public void onError(VolleyError error) {
                //适配评论
                mCommentListView.setEmptyViewOnClickListener(FilmDetailActivity.this);
                //加载评论
                mCommentListView.startLoadData(FilmDetailActivity.this, fObjectid, mPageName);
                mScrollView.scrollToFirstView();
            }

            @Override
            public void onSuccess(FilmVideoLocal filmVideoLocal) {
                if(filmVideoLocal!=null&&filmVideoLocal.getResult()!=null) {
                    FilmVideoLocal.FilmVideoBean filmVideoBean = filmVideoLocal.getResult();
                    detailFilmView.setFilmData(null,null,filmVideoBean,null, mScrollView);
                }
                //适配评论
                mCommentListView.setEmptyViewOnClickListener(FilmDetailActivity.this);
                //加载评论
                mCommentListView.startLoadData(FilmDetailActivity.this, fObjectid, mPageName);
                mScrollView.scrollToFirstView();
            }
        });
    }

    /**
     * 获取电影源
     */
    private void getFilmSourceData() {
        HttpUtils.addGetRequest(URIContant.GETVIDEOSOURCE + fObjectid, new TypeToken<FilmSourceBean>() {
        }.getType(), mPageName, new HttpListener<FilmSourceBean>() {
            @Override
            public void onError(VolleyError error) {
                mScrollView.scrollToFirstView();
            }

            @Override
            public void onSuccess(FilmSourceBean filmSourceBean) {
                if(filmSourceBean!=null&&filmSourceBean.getResult()!=null&&filmSourceBean.getResult().size()>0) {
                    List<FilmSourceBean.FilmSource> filmSourceList = filmSourceBean.getResult();
                    detailFilmView.setFilmData(null,null,null,filmSourceList, mScrollView);
                }
                mScrollView.scrollToFirstView();
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back_gg://返回
            case R.id.ll_back_gg_black://返回
                onBackPressed();
                break;
            case R.id.ll_share://分享
                share();
                break;
            case R.id.tv_comment://评论
                if(UserInforManager.getInstance().isLogin()) {
                    showCommentDialog();
                }else {
                    ToastUtils.makeText("请先登录!");
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
        }
    }
    private AppShareUtils mShareUtils;//分享工具

    /**
     * 分享
     */
    private void share() {
        if (mShareUtils == null) {
            mShareUtils = new AppShareUtils(this);
        }
        ShareBean shareBean = null ;
        mShareUtils.showShareDialog(shareBean);
    }


    private CommentListener mCommentListener;//评论监听
    /* 展示评论框 */
    private void showCommentDialog() {
        if (mCommentListener == null) {
            mCommentListener = new CommentListener() {
                @Override
                public void commentStart() {

                }

                @Override
                public void commentFail(VolleyError volley) {

                }

                @Override
                public void commentSuccess(FilmComment newsComment) {
                    //更新页面
                    if (mCommentListView != null) {
                        mCommentListView.addComment(newsComment);
                    }
                }
            };
        }
        CommentUtils.getInstance().showDialog(this, mPageName, fObjectid, mCommentListener);
    }


    @Override
    public void onBackPressed() {
        if (NiceVideoPlayerManager.instance().onBackPressd()) return;
//        if (JCVideoPlayer.backPress()) {
//            return;
//        }
        AppManager.getAppManager().removeLastDetailActivity();
        if (AppManager.getAppManager().isHaveActivity(FilmDetailActivity.class)) {
            super.onBackPressed();
        } else {
            Intent intent = new Intent(this, MainActivity.class);
            AppManager.getAppManager().finishActivity();
            startActivity(intent);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (NiceVideoPlayerManager.instance().onBackPressd()){
                return true;
            }
//            if (JCVideoPlayer.backPress()) {
//                //判断是否有视频全屏
//                return true;
//            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (data != null) {
                UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AnimationUtils.getInstance().stopLooperTimer();
    }

}
